const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const address = require('../../utils/city')
//记录文件数量
var fileNum = 0;

//设置唯一id
var fileId = 0;
Page({
  data: {
    type: '0',
    activeNames: ['1'],
    icon: {
      normal: '/images/report/unselect_2x.png',
      active: '/images/report/select_2x.png',
    },
    showView: true,
    showsite: false,     //控制弹出层是否弹出的值
    showunit: false,     //控制弹出层是否弹出的值

    columns_unit: ['东', '南', '西', '北'],   //选择器中的值
    site: '',     //进行页面显示
    // disabled: 'false',

    /**
    * 控件当前显示的数据
    * provinces:所有省份
    * citys 选择省对应的所有市,
    * areas 选择市对应的所有区
    * areaInfo：点击确定时选择的省市县结果
    * animationAddressMenu：动画
    * addressMenuIsShow：是否可见
    */
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],

    areaInfo: '', //三级地址数据
    detailed: '',  //详细地址
    unit: '',     //受理单位
    project: '',  //项目名称
    Company: '',  //申请单位
    contact: '',  //联系人
    information: '',  //联系方式
    remarks: '',  //备注
    //本地路径
    myJobList: [],
    //服务器路径
    myFile: [],
    param: {},
    //获取的数据
    detail: null,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 默认联动显示湖南
    this.address();
    console.log(options);
    const detail = JSON.parse(options.detail)
    this.setData({
      detail,
      areaInfo: detail.site, //三级地址数据
      detailed: detail.address,  //详细地址
      unit: detail.acceptUnit,     //受理单位
      project: detail.name,  //项目名称
      Company: detail.applyUnit,  //申请单位
      contact: detail.contacts,  //联系人
      information: detail.phone,  //联系方式
      remarks: detail.remark,  //备注
      //服务器路径
      myFile: detail.fileVoList,
    })
  },
  address() {
    var id = address.provinces[0].id
    console.log(id);
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    })
  },
  // 点击所在地区弹出选择框
  select: function (e) {
    // 如果已经显示，不在执行显示动画
    if (this.data.addressMenuIsShow) {
      return false
    } else {
      // 执行显示动画
      this.startAddressAnimation(true)
    }
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      this.animation.translateY(0 + 'vh').step()
    } else {
      this.animation.translateY(40 + 'vh').step()
    }
    this.setData({
      animationAddressMenu: this.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + '·' + that.data.citys[value[1]].name + '·' + that.data.areas[value[2]].name
    that.setData({
      areaInfo: areaInfo,
    })
  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'linear',
    })
    this.animation = animation
  },
  showSite(e) {      //点击选择性别，打开弹出层（选择器）
    this.setData({ showsite: true })
  },
  onSiteClose() {     //点击空白处开闭弹出层（选择器）及选择器左上角的取消
    this.setData({ showsite: false });
  },
  onSiteConfirm(e) {    //选择器右上角的确定，点击确定获取值
    this.setData({
      site: e.detail.value,
      showsite: false
    })
  },

  showUnit(e) {      //点击选择，打开弹出层（选择器）
    this.setData({ showunit: true })
  },
  onUnitClose() {     //点击空白处开闭弹出层（选择器）及选择器左上角的取消
    this.setData({ showunit: false });
  },
  onUnitConfirm(e) {    //选择器右上角的确定，点击确定获取值
    this.setData({
      unit: e.detail.value,
      showunit: false
    })
  },

  submitNewStuInfo(e) {
    //表单输入框提交的内容包含在e参数中
    // console.log(e);
  },

  projectType(event) {
    this.setData({
      type: event.detail,
    });
    console.log(event.detail);
  },
  //详细地址
  getDetailed(e) {
    this.setData({
      detailed: e.detail.value
    })
  },
  //受理单位
  getUnit(e) {
    this.setData({
      unit: e.detail.value
    })
  },
  //项目名称
  getProject(e) {
    this.setData({
      project: e.detail.value
    })
  },
  //单位名称
  getCompany(e) {
    this.setData({
      Company: e.detail.value
    })
  },
  //联系人
  getContact(e) {
    this.setData({
      contact: e.detail.value
    })
  },
  //联系方式
  getInformation(e) {
    this.setData({
      information: e.detail.value
    })
    console.log(e.detail.value);
  },
  remarks(e) {
    this.setData({
      remarks: e.detail
    })
    console.log(e.detail);
  },

  //上传文件到本地
  addFile: function (e) {
    var that = this;
    if (fileNum < 5) {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['doc', 'docx', 'pdf'],
        success(res) {
          console.log(res);
          let tempFilePaths = res.tempFiles[0].path
          let name = res.tempFiles[0].name;
          // fileId++;

          // console.log(that.data.myJobList);
          wx.showLoading({
            title: '上传中..',
            icon: 'none'
          })
          //文件上传
          wx.uploadFile({
            url: api.uploadFile,
            name: 'file',
            filePath: tempFilePaths,
            header: {
              "Content-Type": "multipart/form-data",
            },
            formData: {
              file: tempFilePaths,
              uploadName: name
            },
            success: function (res) {
              console.log(res);
              let myJobListObj = {}
              myJobListObj.fileName = name
              myJobListObj.filePath = tempFilePaths
              that.data.myJobList.push(myJobListObj)

              let File = JSON.parse(res.data)

              let myFileObj = {};
              myFileObj.filePath = File.file_path;
              myFileObj.fileName = File.file_name;

              that.data.myFile.push(myFileObj)
              that.setData({
                myFile: that.data.myFile,
                myJobList: that.data.myJobList
              })
              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 1000,
                success: () => {
                  //文件上传次数
                  fileNum++;
                },
              })
            },
            fail: function (res) {
              console.log(res)
            },
          })
        }
      })
    } else {
      wx.showToast({
        title: '最多上传5个文件',
        icon: 'none',
        duration: 1000
      })

    }
  },
  openDoc(e) {
    let i = e.currentTarget.dataset.index;
    let filePath = this.data.myJobList[i].filePath

    console.log(e);
    //打开文件
    wx.openDocument({
      filePath,
      success: function (res) {
        // console.log(res);
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  // 删除
  del(e) {
    // console.log(e);
    let that = this;
    let id = e.currentTarget.dataset.id;

    let myJobList = that.data.myJobList;
    let myFile = that.data.myFile;
    
    that.setData({
      clickIndex: id
    })

    wx.showModal({
      title: '提示',
      content: '是否确认删除',
      success(res) {

        //确定
        if (res.confirm) {
          myJobList.splice(that.data.clickIndex, 1);
          //须在确定时用才能下次点击才不会失效
          let file_path = myFile.splice(that.data.clickIndex, 1)[0].path;
          fileNum--;
          that.setData({
            myJobList,
            myFile
          })

          util.request(api.deleteByPath, {
            file_path
          }, 'GET').then(res => {
            console.log(res);
            wx.showToast({
              title: '删除成功',
              duration: 1000,
              icon: 'success'
            })
          })

        } else if (res.cancel) {

        }
      }
    })
  },
  //提交数据
  submitBtn() {
    if (util.verifyEmpty(this.data.areaInfo, "项目所在地")) {
      return false
    }
    else if (util.verifyEmpty(this.data.detailed, "详细地址")) {
      return false
    }
    else if (util.verifyEmpty(this.data.unit, "受理单位")) {
      return false
    }
    else if (util.verifyEmpty(this.data.project, "项目名称")) {
      return false
    }
    else if (util.verifyEmpty(this.data.Company, "单位名称")) {
      return false
    }
    else if (util.verifyEmpty(this.data.contact, "业主联系人")) {
      return false
    }
    else if (util.verifyEmpty(this.data.information, "业主联系方式")) {
      return false
    }
    else if (util.verifyEmpty(this.data.myFile, "附件")) {
      return false
    }
    let param = {
      site: '', //三级地址数据
      address: '',  //详细地址
      acceptUnit: '',     //受理单位
      name: '',  //项目名称
      applyUnit: '',  //申请单位
      contacts: '',  //联系人
      phone: '',  //联系方式
      remark: '',  //备注
      fileVoList: [],//服务器文件路径
      type: '',  //项目类型
      id: ''  //修改id
    }
    if(this.data.detail.site === this.data.areaInfo) {
      param.site = '';
    }else {
      param.site = this.data.areaInfo;
    }
    if(this.data.address === this.data.detail.detailed) {
      param.address = '';
    }else {
      param.address = this.data.detailed;
    }
    if(this.data.acceptUnit === this.data.detail.unit) {
      param.acceptUnit = '';
    }else {
      param.acceptUnit = this.data.unit;
    }
    if(this.data.name === this.data.detail.project) {
      param.name = '';
    }else {
      param.name = this.data.project;
    }
    if(this.data.applyUnit === this.data.detail.Company) {
      param.applyUnit = '';
    }else {
      param.applyUnit = this.data.Company;
    }
    if(this.data.contacts === this.data.detail.contact) {
      param.contacts = '';
    }else {
      param.contacts = this.data.contact;
    }
    if(this.data.phone === this.data.detail.information) {
      param.phone = '';
    }else {
      param.phone = this.data.information;
    }
    if(this.data.remark === this.data.detail.remarks) {
      param.remark = '';
    }else {
      param.remark = this.data.remarks;
    }
    if(this.data.fileVoList === this.data.detail.myFile) {
      param.fileVoList = '';
    }else {
      param.fileVoList = this.data.myFile;
    }
    if(this.data.type === this.data.detail.type) {
      param.type = '';
    }else {
      param.type = this.data.type;
    }
    param.id = this.data.detail.id;
    
    util.request(api.project_update, param, 'post').then(res => {
      // console.log(res);
      wx.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 1000
      }).then(res => {
        fileNum = 0;
        wx.wx.reLaunch({
          url: '/pages/list/list',
        })
      }).catch(err => console.log(err));
    })
  }

})